<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
<h3>WebSocket Demo</h3><br/>
<input type="text" id="text"/>
<hr>
<button onclick="send()">发送消息</button>
<hr>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr>
<div id="message"></div>
<script type="text/javascript">
    var webSocket = null;
    if ("WebSocket" in window) {
        webSocket = new WebSocket("ws://10.8.3.41:7080/websocket");
    } else {
        alert('Current browser not support WebSocket!');
    }
    webSocket.onerror = function () {
        showMessage('An error occured on WebSocket connecting !');
    }

    webSocket.onclose = function () {
        showMessage('close WebSocket connection')
    }
    webSocket.onopen = function () {
        showMessage('WebSocket connected...')
    }
    webSocket.onmessage = function (event) {
        showMessage(event.data);
    }
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //显示信息
    function showMessage(innerHtml) {
        document.getElementById("message").innerHTML += innerHtml + "<br/>";
    }

    //发送消息
    function send() {
        var msg = document.getElementById("text").value;
        webSocket.send(msg);
    }

    function closeWebSocket() {
        webSocket.close();
    }


</script>
</body>
</html>